package com.cn.codebrush.练习;

/**
 * @Author Boolean
 * @Date 2022/5/23 10:34
 * @Version 1.0
 */
public class No19删除链表的倒数第N个结点 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        removeNthFromEnd(node1,2);
    }


    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int len = 0;

        ListNode temp = head;
        while(temp != null){
            len++;
            temp = temp.next;
        }

        int removeNum = len-n;
        if(removeNum == 0){
            return head.next;
        }
        ListNode node =head;
        for(int i=1;i<removeNum+1;i++){
            if(i==removeNum){
                node.next = node.next.next;
                break;
            }
            node = node.next;
        }

        return head;

    }
}
